package cn.xclink.kernel.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.xclink.kernel.entity.User;
import cn.xclink.kernel.service.ResourceService;
import cn.xclink.kernel.service.RoleService;
import cn.xclink.kernel.service.UserService;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private ResourceService resourceService;


	/**
	 * 认证回调函数,登录时调用.
	 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

    	UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = userService.findUserByAccount(token.getUsername());
        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }
        if(Boolean.TRUE.equals(user.getAvailable())) {
            throw new LockedAccountException(); //帐号锁定
        }
        return new SimpleAuthenticationInfo(new ShiroUser(user), user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
    }
    
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	
    	// 因为非正常退出，即没有显式调用 SecurityUtils.getSubject().logout()
    	if (!SecurityUtils.getSubject().isAuthenticated()) {
			SecurityUtils.getSubject().logout();
			return null;
		}
    	ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
    	
		if (shiroUser == null || shiroUser.getUserId() == null) {
			return null;
		}
		
		// 添加角色及权限信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleService.findUserRoleNameByUserId(shiroUser.getUserId()));
        authorizationInfo.setStringPermissions(resourceService.findUserPermissionsByUserId(shiroUser.getUserId()));
        return authorizationInfo;
    }
}
